﻿using ApplicationBase.Core.Logs;
using System.Text.Json;
using System.Text.RegularExpressions;

namespace LogDashboard.Application.Utils
{
    public class LogParser
    {
        public List<CacheLog> CacheLogs { get; set; } = new();
        public List<UnitOfWorkLog> UnitOfWorkLogs { get; set; } = new();

        public void Parse(Stream logStream)
        {
            using var reader = new StreamReader(logStream);

            string line; ;
            while ((line = reader.ReadLine()) != null)
            {
                if (MatchCache(line)) continue;
                if (MatchUnitOfWork(line)) continue;
            }
        }

        public bool MatchCache(string line)
        {
            var cacheLogRegex = new Regex(@"<Cache>.*</Cache>");
            var match = cacheLogRegex.Match(line);
            if(match.Success)
            {
                var json = match.Value.Replace("<Cache>", "").Replace("</Cache>", "").Trim();
                var cacheLog = JsonSerializer.Deserialize<CacheLog>(json);
                if(cacheLog != null)
                {
                    CacheLogs.Add(cacheLog);
                    return true;
                }

                return false;
            } 

            return false;
        }

        public bool MatchUnitOfWork(string line)
        {
            var uowLogRegex = new Regex(@"<UOW>.*</UOW>");
            var match = uowLogRegex.Match(line);
            if(match.Success)
            {
                var json = match.Value.Replace("<UOW>", "").Replace("</UOW>", "").Trim();
                var uowLog = JsonSerializer.Deserialize<UnitOfWorkLog>(json);
                if(uowLog != null)
                {
                    UnitOfWorkLogs.Add(uowLog);
                    return true;
                }

                return false;
            }

            return false;
        }
    }
}
